import { createHash, randomBytes } from 'crypto'
import { readFile, writeFile } from 'fs-extra';

export function useSecret() {
    const secret = process.env.JWT_SECRET || '2axWXEATSKCF7YM8BFQsnjpGkCX6PGPd';
    return secret;
}

export function useSha256(password: string, salt: string) {
    const hash = createHash('sha256');
    hash.update(password);
    hash.update(salt)
    return hash.digest('hex');
}

export function useUser(req: any) {
    return req.auth
}

export function useToken(data: any, headers: any) {
    const token = headers.authorization
    if (token) return token.split(' ')[1];
    return data.token
}

export function usePassword(password: string) {
    const salt = useSalt()
    const pwd = useSha256(`${password}`, salt)
    return {
        salt,
        pwd
    }
}
export function useSalt(size: number = 4) {
    return randomBytes(size).toString('hex')
}

export function useUploadRoot(req: any) {
    return req.uploadsRoot;
}

export function toFail<T>(msg: string, data?: T, code: string = `200`) {
    return {
        success: false, message: msg, data: data, code
    }
}

export function toSuccess<T>(data?: T, page?: number, total?: number) {
    return {
        success: true, message: 'Ok', data: data, page, total
    }
}

export function toLogin() {
    return toFail('登陆已失效，请重新登陆', {}, `403`)
}

export async function readJson(path: string) {
    try {
        const content = await readFile(path, { encoding: 'utf8' })
        const str = content.toString()
        return JSON.parse(str)
    } catch (e) {
        return {}
    }
}

export async function saveJson(path: string, value: any) {
    try {
        await writeFile(path, JSON.stringify(value), { encoding: 'utf8' })
    } catch (e) {
        return {}
    }
}